package handler

import (
	"2302a/testyuekao/api/request"
	"2302a/testyuekao/api/resp"
	"2302a/testyuekao/consts"
	"2302a/testyuekao/internal/dao"
	"2302a/testyuekao/internal/model"
	"2302a/testyuekao/internal/queue"
	"github.com/gin-gonic/gin"
)

func AddHouse(c *gin.Context) {
	var req request.AddHouseReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if !(user.UType == 2 || user.UType == 3) {
		resp.Error(c, 100002, "该权限级别不够", nil)
		return
	}
	house := model.Houses{
		UserId:    userId,
		Title:     req.Title,
		Price:     req.Price,
		Area:      req.Area,
		City:      req.City,
		Address:   req.Address,
		Community: req.Community,
		FileUrl:   req.FileUrl,
		VideoUrl:  req.VideoUrl,
	}
	dao.Create(&house)
	resp.Success(c, "房源发布成功", true)
}

func UpdateHouse(c *gin.Context) {
	var req request.UpdateHouseReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if !(user.UType == 2 || user.UType == 3) {
		resp.Error(c, 100002, "该权限级别不够", nil)
		return
	}
	var house model.Houses
	dao.GetOneById(req.Id, &house)
	if house.Id == 0 {
		resp.Error(c, 100003, "房源不存在", nil)
		return
	}
	if req.Price > 0 && (req.Price != house.Price) {
		queue.PublishPub(consts.UPDATE_HOUSEP_RICE, model.Houses{
			Id:     req.Id,
			UserId: c.GetUint("userId"),
			Price:  req.Price,
		})
	}
	dao.Update(&model.Houses{
		Id:        req.Id,
		UserId:    userId,
		Title:     req.Title,
		Price:     req.Price,
		Area:      req.Area,
		City:      req.City,
		Address:   req.Address,
		Community: req.Community,
		FileUrl:   req.FileUrl,
		VideoUrl:  req.VideoUrl,
	})
	resp.Success(c, "房源价格修改成功", true)

}
func ListHouse(c *gin.Context) {
	var req request.ListHouseReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var list []model.Houses
	dao.GetListByFields(&model.Houses{Title: req.Title}, &list)
	resp.Success(c, "房源列表成功", list)
}

func DetailsHouse(c *gin.Context) {
	var req request.DetailsHouseReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if !(user.UType == 2 || user.UType == 3) {
		resp.Error(c, 100002, "该权限级别不够", nil)
		return
	}
	var house model.Houses
	dao.GetOneById(req.Id, &house)
	if house.Id == 0 {
		resp.Error(c, 100003, "房源不存在", nil)
		return
	}
	resp.Success(c, "房源详情成功", house)
}
